// Create a new Player object.
// @param conn Connection The TELNET connection associated with this player.
// @return this
function Player(conn)
{
	// setup connection link
	this._conn = conn;
	conn._player = this;

	// configure Connection callbacks
	this._conn.onInput = function(line){this._player.onInput(line);};
	this._conn.onFlush = function(){this._player.onFlush();};
	this._conn.onHangup = function(){this._player.disconnect();};

	// allocate player id
	this.pid = Player._nextid++;

	// generate player name
	this.name = 'Player '+this.pid;

	// send greeting
	Help.display(this, 'greeting');

	// add to global list of players
	Player._all[this.pid] = this;
	Player.sendToAll(this.name+' entered the room.\n');

	return this;
}

// List of all players currently logged on.
Player._all = {};

// Next available player id (pid)
Player._nextid = 1;

// Send text to the player.
// @param text String Text to display to the user.
// @return this
Player.prototype.send = function(text)
{
	if (!this._conn) return;

	if (!this._needUpdate) {
		this._conn.send('\n');
		this._needUpdate = true;
	}

	this._conn.send(text);
	return this;
}

// Parse user's command line input.
// @param line String Command line.
Player.prototype.onInput = function(line)
{
	this._needUpdate = true;

	if (line == '/quit') {
		this.disconnect();
	} else if (line == '/who') {
		for each (var p in Player._all)
			this.send(p.name+'\n');
	} else {
		this.send('You said, "'+line+'"\n');

		for each (var p in Player._all)
			if (p !== this)
				p.send(this.name+' said, "'+line+'"\n');
	}
}

// Display the prompt
Player.prototype.onFlush = function()
{
	if (this._needUpdate) {
		this._needUpdate = false;
		this._conn.send('> ');
	}
}

// Remove the player from the list of players.
Player.prototype.disconnect = function()
{
	if (this._conn)
		this._conn.disconnect();

	delete this._conn;
	delete Player._all[this.pid];

	Player.sendToAll(this.name+' left the room.\n');
}

// Send text to all players
// @param text String text to send
Player.sendToAll = function(text)
{
	for each (var p in Player._all)
		p.send(text);
}
